package com.test45_JUC;

import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;

/**
 * BlockingDeque，双端阻塞队列
 */
public class Demo22_BlockingDeque {

    public static void main(String[] args) {
        test1();
    }

    /**
     * LinkedBlockingDeque
     */
    public static void test1() {
        BlockingDeque<String> queue = new LinkedBlockingDeque<>();
        // 生产者1
        for (int x = 0; x < 10; x++) {
            final int temp = x;
            new Thread(() -> {
                for (int y = 0; y < 100; y++) {  // 持续生产
                    try {
                        TimeUnit.SECONDS.sleep(2);
                        String msg = String.format("{ID = MUYAN - %d - %d}沐言科技：www.yootk.com", temp, y);
                        queue.putFirst(msg);
                        System.out.printf("【%s】%s%n", Thread.currentThread().getName(), msg);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }, "FIRST-YOOTK生产者-"+x).start();
        }
        // 生产者2
        for (int x = 0; x < 10; x++) {
            final int temp = x;
            new Thread(() -> {
                for (int y = 0; y < 100; y++) {  // 持续生产
                    try {
                        TimeUnit.SECONDS.sleep(2);
                        String msg = String.format("{ID = MUYAN - %d - %d}沐言科技：www.yootk.com", temp, y);
                        queue.putLast(msg);
                        System.out.printf("【%s】%s%n", Thread.currentThread().getName(), msg);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }, "LAST-YOOTK生产者-"+x).start();
        }
        // 消费者
        for (int x = 0; x < 2; x++) {
            new Thread(() -> {
                int count = 0;
                while (true) {  // 持续性的通过队列取数据
                    if (count % 2 == 0) {
                        try {
                            TimeUnit.SECONDS.sleep(2);
                            System.err.printf("【%s】%s%n", Thread.currentThread().getName(), queue.takeFirst());
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    } else {
                        try {
                            TimeUnit.SECONDS.sleep(2);
                            System.err.printf("【%s】%s%n", Thread.currentThread().getName(), queue.takeLast());
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    count++;
                }
            }, "YOOTK消费者-"+x).start();
        }
    }
}
